package com.shunhe.zs_pda.ui.sys

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.widget.NestedScrollView
import com.ruitu.arad.Arad
import com.ruitu.arad.util.ViewUtils
import com.ruitu.router_module.bean.EventModel
import com.shunhe.zs_pda.R
import com.shunhe.zs_pda.base.Base2Activity
import com.shunhe.zs_pda.model.User
import com.shunhe.zs_pda.ui.sys.p.LoginP
import com.shunhe.zs_pda.util.find
import com.shunhe.zs_pda.util.log
import com.shunhe.zs_pda.util.toast

class LoginActivity : Base2Activity() {
    lateinit var nsv_content: NestedScrollView
    lateinit var et_phone: AppCompatEditText
    lateinit var et_code: AppCompatEditText
    lateinit var tv_ok: TextView

    var account: String? = null
    var pwd: String? = null // 账号 密码

    lateinit var p0: LoginP

    override fun getLayoutRes(): Int = R.layout.activity_login
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        p0 = LoginP(this)
        nsv_content = find(R.id.nsv_content)
        et_phone = find(R.id.et_phone)
        et_code = find(R.id.et_code)
        tv_ok = find(R.id.tv_ok)
        setHeadTitle("登录")
        val account = Arad.preferences.getString("account")
        if (!TextUtils.isEmpty(account)) { // 自动填写记住的用户名
            et_phone.setText(account)
        }
        setListeners()
    }

    private fun setListeners() {
        setOnClickListener(tv_ok)
    }

    override fun onClick(v: View) {
        super.onClick(v)
        if (v === tv_ok) {
            account = ViewUtils.getTvTxt(et_phone)
            pwd = ViewUtils.getTvTxt(et_code)
            if (TextUtils.isEmpty(account)) {
                "请输入账号".toast()
                return
            }
            if (TextUtils.isEmpty(pwd)) {
                "请输入密码".toast()
                return
            }
            p0.reqLogin(account!!, pwd!!)
        }
    }

    fun onRes(code: Int, data: Any) {
        when (code) {
            1 -> {
                val u: User = data as User
                val user = u.userinfo
                log("user.token = ${user.token}")
                Arad.preferences.putString("token", user.token).flush() // 保存token
                Arad.preferences.putString("account", account).flush() // 记住用户名
                Arad.bus.post(EventModel<Any?>(22111151))
                finish()
            }
        }
    }

}